package Modules::GTF2fasta;
use Data::Dumper;
use strict;
use Bio::Seq;
use Bio::SeqIO;
use Bio::DB::Fasta;

sub new {
  my ($class,$util) = @_;
  my $self = {
               util => $util,
             };
  bless $self,$class;
  return $self;
}

sub run {
  my $self           = shift;
  my $util           = $self->{'util'};
  my $source_path    = $util->{'SOURCE_PATH'};
  my $data_path      = $util->{'DATA_PATH'};
  my $genome         = $data_path ."/". $util->{'GENOME'};
  my $gtf            = $data_path ."/". $util->{'GTF'};
  
  my $db             = Bio::DB::Fasta->new($genome);
  print "Genome fasta parsed\n";
  my $outfile_transc = Bio::SeqIO->new( -format => 'fasta', -file => ">$gtf.fa" );
  
  open GFF, "<$gtf" or die $!;
  
  
  while ( my $line = <GFF> ) {
    chomp $line;
    my @array = $line =~ /(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/;
    my $type = $array[2];
    #print Dumper \@array;
    if ($type eq 'transcript') {
     
        my $attrs             = $array[8];
        my ($transcript_name) = $attrs =~ /gene_id \"(\S+)\"/;
        my $transcript_start  = $array[3];
        my $transcript_end    = $array[4];
        my $transcript_seq    = $db->seq( $array[0], $transcript_start, $transcript_end );
        my $output_transc     = Bio::Seq->new(
                -seq        => $transcript_seq,
                -id         => $transcript_name,
                -display_id => $transcript_name,
                -alphabet   => 'dna',
            );
        warn $transcript_name;
        print Dumper $output_transc;
        # Reverse Complement if the frame is minus
        if($array[6] eq '+') {
        }
        elsif ($array[6] eq '-') {
            $output_transc = $output_transc->revcom();
        }
        else {
            die "Unknown frame! At line $. of the GFF\n";
        }
        $outfile_transc->write_seq($output_transc);
        print Dumper \$output_transc;
    } else {
      #print "WARNING: not found any 'transcript' type inside the cufflinks output"
    }

}
close GFF;

  
}

1;